﻿using Microsoft.Extensions.Caching.StackExchangeRedis;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace Project.Core.Config.Config.Cache {
    public class RedisCacheHelper : ICacheHelper {

        private readonly IDatabase _database;
        private readonly ConnectionMultiplexer _connection;
        private readonly string _instanceName;

        public RedisCacheHelper(RedisCacheOptions options, int database = 0) {
            this._connection = ConnectionMultiplexer.Connect(options.Configuration);
            this._database = _connection.GetDatabase(database);
            this._instanceName = options.InstanceName;
        }

        public TValue Get<TValue>(string key) {
            string json = _database.StringGet(_instanceName + key);
            return JsonConvert.DeserializeObject<TValue>(json);
        }

        public List<TValue> Get<TValue>(List<string> keys) {
            List<TValue> list = new List<TValue>();
            foreach (string key in keys) {
                TValue value = JsonConvert.DeserializeObject<TValue>(_database.StringGet(_instanceName + key));
                list.Add(value);
            }
            return list;
        }

        public bool IsExist(string key) {
            return _database.KeyExists(_instanceName + key);
        }

        public bool Remove(string key) {
            try {
                _database.KeyDelete(_instanceName + key);
                return true;
            } catch {
                return false;
            }
        }

        public bool Remove(List<string> keys) {
            try {
                foreach (string key in keys) {
                    _database.KeyDelete(_instanceName + key);
                }
                return true;
            } catch {
                return false;
            }
        }

        public bool Set<TValue>(string key, TValue value, int expires = 0, bool isSliding = false) {
            return _database.StringSet(_instanceName + key, JsonConvert.SerializeObject(value));
        }
    }
}
